package com.cnn.base.common;

import com.cnn.base.util.JsonUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 异常处理的类
 * controller抛出的异常会抛给这个类中的resolvEsception方法
 */
@Component
public class ExceptionHandler implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(JsonUtil.error("服务端异常"));
        } catch (IOException e) {
            //e.printStackTrace();
        }finally{
            if (out == null){
                out.close();
            }

        }


        return null;
    }
}
